//
//  GongHaiViewController.m
//  JuBoCRM
//
//  Created by iMac on 2024/1/24.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "GongHaiViewController.h"
#import "GongHaiListTableViewCell.h"
#import "KeHuLeiXingShaiXuanView.h"
#import "GongHaiShaiXuanView.h"
#import "GongHaiKeHuXiangQingViewController.h"
#import "GongHaiPiLiangLingQuTableViewCell.h"
#import "ChaKanYiXuanChengYanView.h"
#import "AlertRemindView.h"
#import "ZiDingYiXuanChengYuanViewController.h"
@interface GongHaiViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>{
    KeHuLeiXingShaiXuanView *leiXingShaiXuanView;
    GongHaiShaiXuanView *shaiXuanView;
    int page;
    NSMutableArray *dataSource;
    NSString *sceneId;
    NSDictionary *shaiXuanTiaoJianDic;
}
@property (weak, nonatomic) IBOutlet UIButton *keHuShaiXuanButton;
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingTableView *mainTableView;
@property (weak, nonatomic) IBOutlet UIButton *shaiXuanButton;

@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewHeight;

@property (weak, nonatomic) IBOutlet UIButton *keHuLeiXingButton;
@property (nonatomic,assign) BOOL isPiLingLingQu;

@property (weak, nonatomic) IBOutlet UILabel *yiXuanZeNumLabel;
@end

@implementation GongHaiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.customNavBar.hidden = YES;
    
    if (@available(iOS 11.0, *)) {
        self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"GongHaiListTableViewCell" bundle:nil] forCellReuseIdentifier:@"GongHaiListTableViewCell"];
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"GongHaiPiLiangLingQuTableViewCell" bundle:nil] forCellReuseIdentifier:@"GongHaiPiLiangLingQuTableViewCell"];
    
    
    
    leiXingShaiXuanView = [KeHuLeiXingShaiXuanView view];
   
    leiXingShaiXuanView.manageClickBlock = ^(NSString * _Nonnull result, NSString * _Nonnull resultName) {
        _keHuShaiXuanButton.selected = NO;
        leiXingShaiXuanView.hidden = YES;
        if(result.length > 0){
            sceneId = result;
            if(_selelctCurrentPoolBlock){
                _selelctCurrentPoolBlock(sceneId);
            }
            [_keHuLeiXingButton setTitle:resultName forState:UIControlStateNormal];
       
            [self downRefresh];
        }
    };
    
    [self.view addSubview:leiXingShaiXuanView];
    leiXingShaiXuanView.type = 1;
    leiXingShaiXuanView.sd_layout
    .leftEqualToView(_mainTableView)
    .rightEqualToView(_mainTableView)
    .topEqualToView(_mainTableView)
    .bottomEqualToView(_mainTableView);
    leiXingShaiXuanView.hidden = YES;
    
    shaiXuanView = [GongHaiShaiXuanView view];
    [self.view addSubview:shaiXuanView];
    shaiXuanView.sd_layout
    .leftEqualToView(_mainTableView)
    .rightEqualToView(_mainTableView)
    .topEqualToView(_mainTableView)
    .bottomEqualToView(_mainTableView);
    shaiXuanView.hidden = YES;
    
    shaiXuanView.toSelectYuanGongBuMenBlock = ^{
        ZiDingYiXuanChengYuanViewController *shaiXuan = [[ZiDingYiXuanChengYuanViewController alloc] init];
        shaiXuan.manageResultBlock = ^(NSArray * _Nonnull yuanGongArray, NSArray * _Nonnull buMenArray) {
            shaiXuanView.buMenChangYuan = [NSString stringWithFormat:@"已选择：%ld人，%ld部门",yuanGongArray.count,buMenArray.count];
            shaiXuanView.chengYuanArray = yuanGongArray;
            shaiXuanView.buMenArray = buMenArray;
        };
        [self pushViewController:shaiXuan];
    };
    
//    根据条件进行筛选
    shaiXuanView.manageResultBlock = ^(NSDictionary * _Nonnull resultDic) {
        shaiXuanView.hidden = YES;
        shaiXuanTiaoJianDic = resultDic;
        _shaiXuanButton.selected = NO;
        [self downRefresh];
    };
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pingLiangLingQu:) name:@"shiFouPiLiangQu" object:nil];
    
    
    CGFloat radius = 10; // 圆角值大小
    if (@available(iOS 11.0, *)){
        // 设置 左上 右上 圆角
        _bottomView.layer.cornerRadius = radius;
        _bottomView.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    }else {
        // 设置 左上 右上 圆角
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0,0,ScreenWidth,60) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(radius, radius)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = CGRectMake(0,0,ScreenWidth,60);
        maskLayer.path = path.CGPath;
        _bottomView.layer.mask = maskLayer;
    }
    
    _bottomView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.1100].CGColor;
    _bottomView.layer.shadowOffset = CGSizeMake(2,0);
    _bottomView.layer.shadowOpacity = 1;
    _bottomView.layer.shadowRadius = 10;
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self downRefresh];
    }];

    _mainTableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self upRefresh];
    }];
    _mainTableView.mj_footer = footer;
    [self huoQuSouYouSouSuoTiaoJian];

}




//查询搜索条件
- (void)huoQuSouYouSouSuoTiaoJian{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:@"2" forKey:@"type"];
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:@"/crmCustomerPool/queryPoolNameListByAuth" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
        
            leiXingShaiXuanView.dataSource = [info objectForKey:@"data"];
            
            if(leiXingShaiXuanView.dataSource.count > 0){
                sceneId = GetHandleString(leiXingShaiXuanView.dataSource.firstObject, @"poolId");
                if(_selelctCurrentPoolBlock){
                    _selelctCurrentPoolBlock(sceneId);
                }
                [_keHuLeiXingButton setTitle:GetHandleString(leiXingShaiXuanView.dataSource.firstObject, @"poolName") forState:UIControlStateNormal];
                page = 1;
                [self getInfoFromServer];
            }
                
        }
    }];
}


//上拉刷新
- (void)upRefresh {
    page++;
    [self getInfoFromServer];
}

//下拉刷新
- (void) downRefresh {
    page = 1;
    [self getInfoFromServer];
}

- (void)getInfoFromServer{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionaryWithDictionary:shaiXuanTiaoJianDic];
    [paraDic setValue:[NSString stringWithFormat:@"%d",page] forKey:@"page"];
    [paraDic setValue:@10 forKey:@"limit"];
    [paraDic setValue:@"9" forKey:@"type"];
    [paraDic setValue:sceneId forKey:@"poolId"];
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/crmCustomerPool/queryPageList" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if (!error) {
            NSLog(@"info:%@",info);
            NSArray *array = [[info objectForKey:@"data"] objectForKey:@"list"];
            if (page == 1) {
                if ([array count]> 9) {
                    dataSource = [NSMutableArray arrayWithArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshing];
                }else {
                    dataSource = [NSMutableArray arrayWithArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshingWithNoMoreData];
//                    if(dataSource.count == 0){
//                        _mainTableView.mj_footer.hidden = YES;
//                    }else{
//                        _mainTableView.mj_footer.hidden = NO;
//                    }
                }
            }else {
                if ([array count]> 9) {
                    [dataSource addObjectsFromArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshing];
                }else {
                    NSArray *tempArray = array;
                    if (tempArray.count > 0) {
                        [dataSource addObjectsFromArray:tempArray];
                    }
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            
            [_mainTableView reloadData];
            
            
        }else {
            [_mainTableView.mj_header endRefreshing];
            [_mainTableView.mj_footer endRefreshing];
        }
    }];
}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)pingLiangLingQu:(NSNotification *)noti{
    _isPiLingLingQu = YES;
    _bottomView.hidden = NO;
    _bottomViewHeight.constant = 60;
    
    [_mainTableView reloadData];
}





//用户类型筛选
- (IBAction)shaoXuanTiaoJian:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    leiXingShaiXuanView.hidden = !sender.selected;
    _shaiXuanButton.selected = NO;
    shaiXuanView.hidden = YES;

}
//展开已选人员
- (IBAction)zhanKai:(UIButton *)sender {
    
    NSMutableArray *listAray = [NSMutableArray array];
    for (NSDictionary *dataDic in dataSource) {
        if([GetHandleString(dataDic, @"isSelected") boolValue]){
            [listAray addObject:dataDic];
        }
    }

    ChaKanYiXuanChengYanView *chaKan = [ChaKanYiXuanChengYanView view];
    chaKan.gongHaiChaKanBottomView.hidden = NO;
    chaKan.gongHaiNumLabel.text = _yiXuanZeNumLabel.text;
    chaKan.titleLabel.text = _yiXuanZeNumLabel.text;
    chaKan.firstArray = listAray;
    chaKan.manageClickBlock = ^(NSInteger index) {
        [self dismissViewControllerAnimated:YES completion:nil];
        if(index == 102){
            //            退出
            [self tuiChu:nil];
        }else  if(index == 103){
            //            批量领取
            [self piLiangLingQuClick:nil];
        }
    };
    chaKan.removeObjectBlock = ^(NSDictionary * _Nonnull dataDictionary) {
        NSInteger index = [dataSource indexOfObject:dataDictionary];
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dataDictionary];
        [dataDic setValue:[NSString stringWithFormat:@"%d",![GetHandleString(dataDic, @"isSelected") boolValue]] forKey:@"isSelected"];
        [dataSource replaceObjectAtIndex:index withObject:dataDic];
        [UIView performWithoutAnimation:^{
            [_mainTableView reloadData];
        }];
        [self duiShaiXuanShuJuJinXingHuoQu];
    };
    [ZZPUtils showActionSheetWithView:chaKan andController:self];
}
//退出
- (IBAction)tuiChu:(id)sender {
    _isPiLingLingQu = NO;
    _bottomView.hidden = YES;
    _bottomViewHeight.constant = 0;
    
    [_mainTableView reloadData];
}
//领取
- (IBAction)piLiangLingQuClick:(UIButton *)sender {
    NSMutableArray *listAray = [NSMutableArray array];
    for (NSDictionary *dataDic in dataSource) {
        if([GetHandleString(dataDic, @"isSelected") boolValue]){
            [listAray addObject:GetHandleString(dataDic, @"customerId")];
        }
    }
    
    [self piLiangLingQuWithUserId:listAray andPoolId:nil];

}
//是否领取成功
- (void)shiFouLingQuChengGong:(BOOL)isSuccess{
    AlertRemindView *view = [AlertRemindView view];
    [ZZPUtils showAlertViewWithView:view andController:self];
    view.leftButton.hidden = YES;
    view.rightButton.hidden = YES;
    view.centerButton.hidden = NO;
    if(isSuccess){
        view.topImage.image = LocalImagePath(@"公海领取弹窗成功");
        view.titleLabel.text = @"领取成功";
        view.contentLabel.text = @"恭喜领取成功！";
    }else{
        view.topImage.image = LocalImagePath(@"公海领取弹窗失败");
        view.titleLabel.text = @"领取失败";
        view.contentLabel.text = @"超过库容，领取失败";
    }
    view.manageClickBlock = ^(NSInteger index) {
        [self dismissViewControllerAnimated:YES completion:nil];
    };
}


//筛选
- (IBAction)shaiXuan:(UIButton *)sender {
    sender.selected = !sender.selected;
    _keHuLeiXingButton.selected = NO;
    _keHuShaiXuanButton.selected = NO;
    leiXingShaiXuanView.hidden = YES;
    shaiXuanView.poolId = sceneId;
    shaiXuanView.hidden = !sender.selected;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_isPiLingLingQu){
        return 124;
    }
    return 182;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_isPiLingLingQu){
        GongHaiPiLiangLingQuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GongHaiPiLiangLingQuTableViewCell"];
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dataSource[indexPath.row]];
        cell.nameLabel.text = GetHandleString(dataDic, @"customerName");
        cell.phoneLabel.text = GetHandleString(dataDic, @"mobile");
        cell.genJinTimeLabel.text = GetHandleString(dataDic, @"lastTime");
        cell.statusLabel.text = GetHandleString(dataDic, @"level");
        cell.selectButton.selected = [GetHandleString(dataDic, @"isSelected") boolValue];
        cell.manageClickBlock = ^{
            [dataDic setValue:[NSString stringWithFormat:@"%d",![GetHandleString(dataDic, @"isSelected") boolValue]] forKey:@"isSelected"];
            [dataSource replaceObjectAtIndex:indexPath.row withObject:dataDic];
            [UIView performWithoutAnimation:^{
                [_mainTableView reloadData];
            }];
            [self duiShaiXuanShuJuJinXingHuoQu];
        };
        return cell;
    }
    GongHaiListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GongHaiListTableViewCell"];
    NSDictionary *dataDic = dataSource[indexPath.row];
    cell.nameLabel.text = GetHandleString(dataDic, @"customerName");
    cell.phoneLabel.text = GetHandleString(dataDic, @"mobile");
    cell.statusLabel.text = GetHandleString(dataDic, @"level");
    cell.fuZeRenLabel.text = GetHandleString(dataDic, @"lastTime");
    cell.manageClickBlock = ^{
//        领取
        
        [self piLiangLingQuWithUserId:@[GetHandleString(dataDic, @"customerId")] andPoolId:[NSString stringWithFormat:@"%ld",indexPath.row]];
        
    };
    return cell;
}
//查看已选择的成员
- (void)duiShaiXuanShuJuJinXingHuoQu{
    NSMutableArray *listAray = [NSMutableArray array];
    for (NSDictionary *dataDic in dataSource) {
        if([GetHandleString(dataDic, @"isSelected") boolValue]){
            [listAray addObject:dataDic];
        }
    }
    _yiXuanZeNumLabel.text = [NSString stringWithFormat:@"已选择：%ld人",listAray.count];
}


//批量领取
- (void)piLiangLingQuWithUserId:(NSArray *)userList andPoolId:(NSString *)currentIndex{
    
    if(userList.count == 0){
        [ZZPUtils showWarning:@"请先选择要领取的客户"];
        return;
    }
    
    AlertRemindView *view = [AlertRemindView view];
    [ZZPUtils showAlertViewWithView:view andController:self];
    view.manageClickBlock = ^(NSInteger index) {
        [self dismissViewControllerAnimated:YES completion:^{
            if(index == 102){
    //            确定
                NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
                [paraDic setValue:userList forKey:@"ids"];
                [paraDic setValue:sceneId forKey:@"poolId"];
                [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/crmCustomer/receiveByIds" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
                    if(!error){
                        if([currentIndex length] > 0){
                            [dataSource removeObjectAtIndex:[currentIndex integerValue]];
                            [UIView performWithoutAnimation:^{
                                [_mainTableView reloadData];
                            }];
                        }else{
                            [self downRefresh];
                            [self tuiChu:nil];
                        }
                        [self shiFouLingQuChengGong:YES];
                        _yiXuanZeNumLabel.text = @"已选择：0人";
                    }else{
                        [self shiFouLingQuChengGong:NO];
                    }
                }];
            }
        }];
    };
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    GongHaiKeHuXiangQingViewController *xiangQing = [[GongHaiKeHuXiangQingViewController alloc] init];
    NSDictionary *dataDic = dataSource[indexPath.row];
    xiangQing.customerId = GetHandleString(dataDic, @"customerId");
    xiangQing.poolId = GetHandleString(dataDic, @"poolId");
    xiangQing.manageClickResultBlock = ^(NSInteger result) {
        [self downRefresh];
    };
    [self pushViewController:xiangQing];
}

-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"暂无搜索"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"暂无公海客户~"attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:16],NSForegroundColorAttributeName: rgba(163, 168, 185, 1)}];
    return string;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


